﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace TopShooter.RenderControls
{
	public class GameDraw : GraphicsDeviceControl
	{
		private Game _game;

		private System.Timers.Timer timerInvalidator;

		static public bool PauseRendering;

		protected override void Initialize()
		{
			timerInvalidator = new System.Timers.Timer();
			timerInvalidator.Elapsed += new System.Timers.ElapsedEventHandler(timerInvalidator_Elapsed);
			timerInvalidator.Interval = 10;
			timerInvalidator.AutoReset = true;
			timerInvalidator.Start();

			_game = new Game(this);
			_game.LoadContent();
			_gameTime = new GameTime();
			_lastUpdateTicks = System.Environment.TickCount;

		}
		GameTime _gameTime;
		public GameTime GameTime { get { return _gameTime; } }
		public float TimeDelta;

		private long _timeElapsed;
		private int _lastUpdateTicks;

		private bool _isFirstDraw = true;

		private void OnFirstDraw()
		{
			_isFirstDraw = false;
			//_game.LoadContent();
		}

		protected override void UpdateGameLoop()
		{
			if (_isFirstDraw)
				OnFirstDraw();

			int ticksNow = System.Environment.TickCount;
			int ticksElapsed = ticksNow - _lastUpdateTicks;
			_lastUpdateTicks = ticksNow;
			_timeElapsed += ticksElapsed;

			_gameTime = new GameTime(TimeSpan.FromMilliseconds(_timeElapsed), TimeSpan.FromMilliseconds(ticksElapsed));
			TimeDelta = ticksElapsed * 0.001f;

			_game.Update(_gameTime);
		}
		protected override void Draw()
		{
			_game.Draw();
		}
		private void timerInvalidator_Elapsed(object sender, EventArgs e)
		{
			FrameworkDispatcher.Update();
			Invalidate();
		}
	}
}
